package com.liuning.graduationdemo.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuning.graduationdemo.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.liuning.graduationdemo.service.ICommentService;
import com.liuning.graduationdemo.entity.Comment;
import org.springframework.web.bind.annotation.RequestMapping;
import com.liuning.graduationdemo.common.Result;
import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pumpkin
 * @since 2022-04-19
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private ICommentService commentService;

    /**
     * 保存或更新
     * @param comment
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody Comment comment) {
        if (comment.getId() == null) {
            //表示是新增
            comment.setUserId(TokenUtils.getCurrentUser().getId());
            comment.setTime(DateUtil.now());

            //判断是评论还是回复
            if (comment.getPid() != null) {
                //说明是回复
                //当前评论的pid
                Integer pid = comment.getPid();
                //根据pid找到一级评论
                Comment pComment = commentService.getById(pid);
                //设置originId（一级评论的id）
                if (pComment.getOriginId() != null) {
                    //如果当前评论的父级还有父级，则设置当前评论的祖宗为当前评论父级的祖宗，来源一个祖宗
                    comment.setOriginId(pComment.getOriginId());
                }else {
                    //如果没有则设置当前评论的父级为祖宗
                    comment.setOriginId(comment.getPid());
                }
            }
        }
        return Result.success(commentService.saveOrUpdate(comment));
    }

    /**
     * 删除单条数据
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        commentService.removeById(id);
        return Result.success();
    }

    /**
     * 查询全部数据
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(commentService.list());
    }

    /**
     * 查询树形结构
     * @return
     */
    @GetMapping("/tree/{articleId}")
    public Result findTree(@PathVariable(name = "articleId") Integer articleId) {
        //全部评论数据
        List<Comment> articleComments = commentService.findCommentDetail(articleId);
        //一级评论
        List<Comment> originList = articleComments.stream().filter(comment -> comment.getOriginId() == null).collect(Collectors.toList());
        //给一级评论设置子节点，也就是回复的评论
        for (Comment origin : originList) {
            //回复的评论
            List<Comment> childrenList = articleComments.stream().filter(comment -> origin.getId().equals(comment.getOriginId())).collect(Collectors.toList());
            childrenList.forEach(comment -> {
                //找到父级评论的用户id和用户名，并设置给当前的回复对象
                articleComments.stream().filter(c1 -> c1.getId().equals(comment.getPid())).findFirst().ifPresent((v -> {
                    comment.setPUserId(v.getUserId());
                    comment.setPUsername(v.getUsername());
                }));
            });

            origin.setChildren(childrenList);
        }
        return Result.success(originList);
    }

    /**
     * 根据id查询一条数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(commentService.getById(id));
    }

    /**
     * 分页查找所有数据
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(commentService.page(new Page<>(pageNum, pageSize),queryWrapper));
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        commentService.removeBatchByIds(ids);
        return Result.success();
    }


}

